//
//  TimingPatternDetailViewController.m
//  Portable Traffic Signal Assistor
//
//  Created by Hao Xu on 4/20/12.
//  Copyright (c) 2012 TTU. All rights reserved.
//

#import "TimingPatternDetailViewController.h"

@interface TimingPatternDetailViewController ()

@end

@implementation TimingPatternDetailViewController
@synthesize sections=_sections;
@synthesize timingPatternNameSection=_timingPatternNameSection;
@synthesize timeRangeListSection=_timeRangeListSection;
@synthesize signalListSection=_signalListSection;
@synthesize signalList=_signalList;
@synthesize addSignalButton=_addSignalButton;
@synthesize addTimeRangeButton=_addTimeRangeButton;
@synthesize timingPattern=_timingPattern;
@synthesize subSystem=_subSystem;
@synthesize agency=_agency;
@synthesize publicSender=_publicSender;
@synthesize timingPatternNameTextView=_timingPatternNameTextView;
@synthesize cycleLengthNameSection=_cycleLengthNameSection;
@synthesize timingPatternCycleTextView=_timingPatternCycleTextView;
@synthesize timer=_timer;
@synthesize masterTimeLabel=_masterTimeLabel;
@synthesize editScheduleButton=_editScheduleButton;
@synthesize editSignalButton=_editSignalButton;
@synthesize signalCellList=_signalCellList;
@synthesize dynamicSignalCellList=_dynamicSignalCellList;
@synthesize linkButtonSection=_linkButtonSection;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void) dealloc
{
    [_sections release];
    [_timingPatternNameSection release];
    [_timeRangeListSection release];
    [_signalListSection release];
    [_signalList release];
    [_addSignalButton release];
    [_addTimeRangeButton release];
    [_timingPattern release];
    [_subSystem release];
    [_agency release];
    [_timingPatternNameTextView release];
    [_cycleLengthNameSection release];
    [_timingPatternCycleTextView release];
    [_timer release];
    [_masterTimeLabel release];
    [_editSignalButton release];
    [_editScheduleButton release];
    [_signalCellList release];
    [_dynamicSignalCellList release];
    [_linkButtonSection release];
    [super dealloc];
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.tableView.backgroundColor = [UIColor clearColor];
    //    UIImageView *backgroundView=[[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"background.png"]] autorelease];
    
    //    [self.navigationController.view addSubview:backgroundView];
    //    [self.navigationController.view sendSubviewToBack:backgroundView];
    self.tableView.opaque = NO;
    self.tableView.backgroundView = nil;
    //    [self.navigationController setNavigationBarHidden:YES animated:YES];
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    
    if (!_timingPatternNameSection) {
        _timingPatternNameSection=[[TableSection alloc]init];
        
        _timingPatternNameSection.contents=[[[NSMutableArray alloc] init] autorelease];
        [_timingPatternNameSection.contents addObject:self.timingPattern.timingPatternName];
        
        _timingPatternNameSection.header=@"Timing Pattern Name";
    }
    
    if (!_cycleLengthNameSection) {
        _cycleLengthNameSection=[[TableSection alloc]init];
        
        _cycleLengthNameSection.contents=[[[NSMutableArray alloc] init] autorelease];
        [_cycleLengthNameSection.contents addObject:self.timingPattern.cycleLength];
        
        _timingPatternNameSection.header=@"Timing Pattern Cycle";
    }
    if(!_timeRangeListSection)
    {
        _timeRangeListSection=[[TableSection alloc]init];
        
        _timeRangeListSection.contents=[[[NSMutableArray alloc] init] autorelease];
        for (int i=0; i<self.timingPattern.timeRangeList.count; i++) {
            NSString * timeRangeString=[NSString stringWithFormat:@"%@ - %@",[[self.timingPattern.timeRangeList objectAtIndex:i] beginTime], [[self.timingPattern.timeRangeList objectAtIndex:i] endTime]];
            [_timeRangeListSection.contents addObject:timeRangeString];
        }
        
        _timeRangeListSection.header=@"Timing Pattern Schedule";
    }
    if(!_signalListSection)
    {
        _signalListSection=[[TableSection alloc]init];
        self.signalList=[NSMutableArray arrayWithArray:[XMLParser getSignalList:self.agency.agencyID subSystemID:self.subSystem.subSystemID timingPatternID:self.timingPattern.timingPatternID]];
        _signalListSection.contents=[[[NSMutableArray alloc] init] autorelease];
        for (int i=0; i<self.signalList.count; i++) {
            [_signalListSection.contents addObject:[[self.signalList objectAtIndex:i] signalName]];
        }
        
//        _signalListSection.header=@"   Signals           Active         Next";
        _signalListSection.header=@"   Signals";
    }
//    if (!_linkButtonSection) {
//        _linkButtonSection=[[TableSection alloc] init];
//        _linkButtonSection.contents=[[[NSMutableArray alloc] init] autorelease];
//        [_linkButtonSection.contents addObject:@"Link Information"];
//        _linkButtonSection.header=@"";
//    }
    if (!_sections) {
        _sections = [[NSMutableArray alloc] init];
        //        [_sections addObject:self.agencyNameSection];
        [_sections addObject:self.timingPatternNameSection];
        [_sections addObject:self.cycleLengthNameSection];
        [_sections addObject:self.timeRangeListSection];
        [_sections addObject:self.signalListSection];
//        [_sections addObject:self.linkButtonSection];
    }
    UITapGestureRecognizer *gestureRecognizer = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(textViewReturn:)] autorelease];
    gestureRecognizer.cancelsTouchesInView = NO;
    [self.tableView addGestureRecognizer:gestureRecognizer];
    [self createSignalCellList];
//    [self updateRealTimeInformation];
//    [self.tableView setEditing:YES];
    
    [self.navigationController setToolbarHidden:NO];
    UIBarButtonItem *buttonItem= [[[ UIBarButtonItem alloc ] initWithTitle: @"Map" style: UIBarButtonItemStyleBordered target: self action: @selector( goToMap:) ] autorelease];
    UIBarButtonItem *activeButtonItem= [[[ UIBarButtonItem alloc ] initWithTitle: @"ActiveMap" style: UIBarButtonItemStyleBordered target: self action: @selector( goToActiveMap:) ] autorelease];
    UIBarButtonItem *space=[[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil] autorelease];
    CustomizedBarButtonItem *timeSpaceButton=[[[CustomizedBarButtonItem alloc] initCustomizedBarButtonItem:[UIImage imageNamed:@"TimeSpaceIcon.png"] target:self action:@selector(goToTimeSpace:)] autorelease];
    CustomizedBarButtonItem *timeSpaceHistoryButton=[[[CustomizedBarButtonItem alloc] initCustomizedBarButtonItem:[UIImage imageNamed:@"TimeSpaceIconHistory.png"] target:self action:@selector(goToTimeSpaceHistory:)] autorelease];
    //    [playButton setStyle:UIBarButtonSystemItemPause];
    
    CustomizedBarButtonItem *homeButtonItem=[[[CustomizedBarButtonItem alloc] initCustomizedBarButtonItem:[UIImage imageNamed:@"home.png"] target:self action:@selector(goToHome:)] autorelease];
//    mapButtonItem=[[UIBarMapButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemStop target:<#(id)#> action:<#(SEL)#>]
    self.toolbarItems = [ NSArray arrayWithObjects: homeButtonItem,space,buttonItem,space, timeSpaceButton,space,timeSpaceHistoryButton,nil ];
//    [ buttonItem release ];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    self.sections=nil;
    self.timingPatternNameSection=nil;
    self.timeRangeListSection=nil;
    self.signalListSection=nil;
    self.signalList=nil;
    self.addSignalButton=nil;
    self.addTimeRangeButton=nil;
    self.timingPattern=nil;
    self.subSystem=nil;
    self.agency=nil;
    self.timingPatternNameTextView=nil;
    self.cycleLengthNameSection=nil;
    self.timingPatternCycleTextView=nil;
    self.timer=nil;
    self.masterTimeLabel=nil;
    self.editScheduleButton=nil;
    self.editSignalButton=nil;
    self.signalCellList=nil;
    self.dynamicSignalCellList=nil;
    self.linkButtonSection=nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)viewWillAppear:(BOOL)animated
{
    [self updateViewController];
    self.timer = [NSTimer timerWithTimeInterval:1.0f target:self selector:@selector(updateTimer:) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
    [self.navigationController setToolbarHidden:NO];
}
- (void)viewWillDisappear:(BOOL)animated
{
    self.timingPattern.timingPatternName=self.timingPatternNameTextView.text;
    self.timingPattern.cycleLength=self.timingPatternCycleTextView.text;
    [XMLParser updateTimingPattern:self.timingPattern agencyID:self.agency.agencyID subSystemID:self.subSystem.subSystemID];
    [self.timer invalidate];
//    [self.navigationController setToolbarHidden:YES];
}
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    
    // Return the number of sections.
    return [self.sections count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    // Return the number of rows in the section.
    NSArray *sectionContents=[[self.sections objectAtIndex:section] contents];
    
    return [sectionContents count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==3) {
        return 94;
    }
    return 44;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell * cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
//    }
    
    
    TableSection *section=[self.sections objectAtIndex:indexPath.section];
    NSArray *sectionContents=[section contents];
    NSString *sectionContentString=[sectionContents objectAtIndex:indexPath.row];
    
    
    [cell setAccessoryType:[section accessoryType]];
    cell.textLabel.numberOfLines=0;
    cell.textLabel.lineBreakMode=UILineBreakModeWordWrap;    
    
    
    switch (indexPath.section) {
            //        case 0:
            //            cell.selectionStyle=UITableViewCellSelectionStyleNone;
            ////            [cell.textLabel setBackgroundColor:[UIColor grayColor]];
            //            [cell setBackgroundColor:[UIColor groupTableViewBackgroundColor]];
            //            break;
        case 0:
        {
            cell.selectionStyle=UITableViewCellSelectionStyleNone;
            
            CGFloat height=[TableSection calculateStringHeight:[[section contents] objectAtIndex:indexPath.row]];
            
            self.timingPatternNameTextView=[[[UITextView alloc] initWithFrame:CGRectMake(1, 5, (CONST_portraitCellWidth-2), (height-10))] autorelease];
            [self.timingPatternNameTextView setText:sectionContentString];
            [self.timingPatternNameTextView setFont:[TableSection TitleFont]];
            //            [self.projectNameTextView setTag:ProjectNameTextView];
            self.timingPatternNameTextView.tag=NameTextView;
            self.timingPatternNameTextView.delegate=self;
            
            [[cell contentView] addSubview:self.timingPatternNameTextView];
            [cell setBackgroundColor:[TableSection WhiteColor]];
            
            return cell;
        }
        case 1:
        {
            cell.selectionStyle=UITableViewCellSelectionStyleNone;
            cell.accessoryType=
            UITableViewCellAccessoryDetailDisclosureButton;
            
//            CGFloat height=[TableSection calculateStringHeight:[[section contents] objectAtIndex:indexPath.row]];
            self.timingPatternCycleTextView=[[[UITextField alloc] initWithFrame:CGRectMake(10, 0, 60, 45)] autorelease];
            [self.timingPatternCycleTextView setText:sectionContentString];
            [self.timingPatternCycleTextView setFont:[TableSection TitleFont]];
            //            [self.projectNameTextView setTag:ProjectNameTextView];
            self.timingPatternCycleTextView.tag=CycleLengthTextView;
            [self.timingPatternCycleTextView setBorderStyle:UITextBorderStyleRoundedRect];
//            self.timingPatternCycleTextView
            self.timingPatternCycleTextView.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
            self.timingPatternCycleTextView.textAlignment = UITextAlignmentCenter;
            self.timingPatternCycleTextView.delegate=self;
            self.timingPatternCycleTextView.backgroundColor=[UIColor whiteColor];
            [self.timingPatternCycleTextView setKeyboardType:UIKeyboardTypeNumberPad];
//            [self.timingPatternCycleTextView setma]
            
            [[cell contentView] addSubview:self.timingPatternCycleTextView];
//            [cell setBackgroundColor:[TableSection WhiteColor]];
            [cell setBackgroundColor:[UIColor groupTableViewBackgroundColor]];
            if ([self.timingPatternCycleTextView.text intValue]>10) {
                int cycleTimer=[TrafficSignalTimer calculateCycleTimer:[self.timingPattern.cycleLength intValue] offSet:0 syncTime:self.agency.syncTime standardTimeOff:[self.agency.baseTimeOffset intValue]];
                cell.textLabel.text=[NSString stringWithFormat:@"              Master:%@ - %d",[TrafficSignalTimer getMasterTimeString:self.agency.baseTimeOffset], cycleTimer];
            }
            
            self.masterTimeLabel=cell.textLabel;
            return cell;
        }
            
            break;
        case 3:
        {
//            RealTimeSignalCell* signalCell = [[[RealTimeSignalCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
//            [signalCell setAccessoryType:[section accessoryType]];
//            
//          
//            RealTimeSignalCell *signalCell=[self.signalCellList objectAtIndex:indexPath.row];
            
//            signalCell.accessoryType=
//            UITableViewCellAccessoryDetailDisclosureButton;
//            signalCell.signalNameLabel.text=sectionContentString;
//            [signalCell setSelectionStyle:UITableViewCellEditingStyleNone];
            
            DynamicSignalCell *dynamicSignalCell=[self.dynamicSignalCellList objectAtIndex:indexPath.row];
            dynamicSignalCell.accessoryType=
            UITableViewCellAccessoryDetailDisclosureButton;
            [dynamicSignalCell setSelectionStyle:UITableViewCellEditingStyleNone];
            
            return dynamicSignalCell;
            
//            return signalCell;
            
        }
            break;
        default:
        {
            cell.accessoryType=
            UITableViewCellAccessoryDisclosureIndicator;
            cell.textLabel.text=sectionContentString;
        }
            break;
    }
    
    return cell;

}
- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.section) {
        case 1:
        {
            TimeAdjustmentViewController *detailViewController=[[[TimeAdjustmentViewController alloc] initWithNibNameAndAgency:@"TimeAdjustmentViewController" timingPattern:self.timingPattern subSystem:self.subSystem agency:self.agency index:indexPath.row bundle:nil] autorelease];
            [detailViewController setTitle:@"Time Adjustment"];
            [self.navigationController pushViewController:detailViewController animated:YES];
            [self.navigationController setNavigationBarHidden:NO animated:YES];
        }
            break;
        case 3:
        {
            self.signalList=[NSMutableArray arrayWithArray:[XMLParser getSignalList:self.agency.agencyID subSystemID:self.subSystem.subSystemID timingPatternID:self.timingPattern.timingPatternID]];
            
            SignalAssistorDetailEditViewController *detailViewController=[[[SignalAssistorDetailEditViewController alloc] initWithNibNameAndSignal:@"SignalAssistorDetailEditViewController" agency:self.agency subSystem:self.subSystem timingPattern:self.timingPattern signal:[self.signalList objectAtIndex:indexPath.row] bundle:nil] autorelease];
            [detailViewController setTitle:@"Edit Signal"];
            [self.navigationController pushViewController:detailViewController animated:YES];
            [self.navigationController setNavigationBarHidden:NO animated:YES];
        }
            
        default:
            break;
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { 
    
    CGRect headerViewRect = CGRectMake(0.0,0.0,320,40);
    UIView* headerView = [[[UIView alloc] initWithFrame:headerViewRect] autorelease];
    headerView.backgroundColor = [UIColor clearColor];
    UILabel *aLabel = [[[UILabel alloc] initWithFrame:CGRectMake(20,0.0,300,40)] autorelease];
    aLabel.text =[[self.sections objectAtIndex:section] header] ;
    aLabel.font = [UIFont boldSystemFontOfSize:16.0];
    aLabel.textAlignment = UITextAlignmentLeft;
    aLabel.backgroundColor = [UIColor clearColor];
    aLabel.textColor=[UIColor darkGrayColor];
    
    
    [headerView addSubview:aLabel];
    
    switch (section) {
        case 0:
        {
            UIButton *duplicateButton=[UIButton buttonWithType:UIButtonTypeRoundedRect];
            [duplicateButton setFrame:CGRectMake(220,4,90,30)];
            [duplicateButton setTitle:@"Duplicate" forState:UIControlStateNormal];
            //        NSArray *timerGroupList=[XMLParser getTimerGroupList];
            //            [newbutton setTag:(section)];
            [duplicateButton addTarget:self action:@selector(clickDuplicateButton)
                              forControlEvents:UIControlEventTouchUpInside];
            [headerView addSubview:duplicateButton];
            return headerView;
        }
            break;
        case 1:
        {
            return headerView;
        }
            break;
        case 2:
        {
            //Then you can add a UILabel to your headerView
            UIButton *newbutton=[UIButton buttonWithType:UIButtonTypeContactAdd];
            [newbutton setFrame:CGRectMake(220,4,30,30)];
            //    [newbutton setTitle:@"Remove" forState:UIControlStateNormal];
            //        NSArray *timerGroupList=[XMLParser getTimerGroupList];
            [newbutton setTag:(section)];
            [newbutton addTarget:self action:@selector(clickAddTimeRangeButton:) 
                forControlEvents:UIControlEventTouchUpInside];
            [headerView addSubview:newbutton];
            
            self.editScheduleButton=[UIButton buttonWithType:UIButtonTypeRoundedRect];
            [self.editScheduleButton setFrame:CGRectMake(270,4,40,30)];
            [self.editScheduleButton setTitle:@"Edit" forState:UIControlStateNormal];
            //        NSArray *timerGroupList=[XMLParser getTimerGroupList];
//            [newbutton setTag:(section)];
            [self.editScheduleButton addTarget:self action:@selector(clickEditScheduleButton) 
                forControlEvents:UIControlEventTouchUpInside];
            [headerView addSubview:self.editScheduleButton];
            
            return headerView;
        }
            break;
        case 3:
        {
            //Then you can add a UILabel to your headerView
            UIButton *newbutton=[UIButton buttonWithType:UIButtonTypeContactAdd];
            [newbutton setFrame:CGRectMake(4,4,30,30)];
            //    [newbutton setTitle:@"Remove" forState:UIControlStateNormal];
            //        NSArray *timerGroupList=[XMLParser getTimerGroupList];
            [newbutton setTag:(section)];
            [newbutton addTarget:self action:@selector(clickAddSignalButton:) 
                forControlEvents:UIControlEventTouchUpInside];
            [headerView addSubview:newbutton];
            
            self.editSignalButton=[UIButton buttonWithType:UIButtonTypeRoundedRect];
            [self.editSignalButton setFrame:CGRectMake(270,4,40,30)];
            if ([self.tableView isEditing]) {
                [self.editSignalButton setTitle:@"Done" forState:UIControlStateNormal];
            }else {
                [self.editSignalButton setTitle:@"Edit" forState:UIControlStateNormal];
            }
            
            //        NSArray *timerGroupList=[XMLParser getTimerGroupList];
            //            [newbutton setTag:(section)];
            [self.editSignalButton addTarget:self action:@selector(clickEditSignalButton) 
                              forControlEvents:UIControlEventTouchUpInside];
            [headerView addSubview:self.editSignalButton];
            
            return headerView;
        }
            break;
            
        default:
            break;
    }
    
   
    
    return headerView;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath 
{
    if (indexPath.section==0) {
        return UITableViewCellEditingStyleNone;
    }
    return UITableViewCellEditingStyleDelete;
    
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.section) {
        case 2:
        {
            if (editingStyle == UITableViewCellEditingStyleDelete) 
            {
                // Commit the delete
                [self removeTimeRange:indexPath.row];
                
            }
        }
            break;
        case 3:
        {
            if (editingStyle == UITableViewCellEditingStyleDelete) 
            {
                // Commit the delete
                [self removeSignal:indexPath.row];
                
            }
        }
            break;
        default:
            break;
    }
    
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { 
    
    
    return [[self.sections objectAtIndex:section] header];
    
}


// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    switch (indexPath.section) {
        case 0:
        case 1:
            return NO;
            break;
        case 2:
        {
            if ([self.editSignalButton.titleLabel.text isEqualToString:@"Done"]) {
                return NO;
            }else {
                return YES;
            }
        }
            break;
        case 3:
        {
            if ([self.editScheduleButton.titleLabel.text isEqualToString:@"Done"]) {
                return NO;
            }else {
                return YES;
            }
        }
            
        default:
            return YES;
            break;
    }

    return YES;
}


/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.
    /*
     <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
     [self.navigationController pushViewController:detailViewController animated:YES];
     [detailViewController release];
     */
    switch (indexPath.section) {
        case 2:
        {
            TimingPatternScheduleViewController *detailViewController=[[[TimingPatternScheduleViewController alloc] initWithNibNameAndTimingPattern:@"TimingPatternScheduleViewController" timingPattern:self.timingPattern subSystem:self.subSystem agency:self.agency index:indexPath.row  bundle:nil] autorelease];
            [detailViewController setTitle:@"Time Schedule"];
            [self.navigationController pushViewController:detailViewController animated:YES];
            [self.navigationController setNavigationBarHidden:NO animated:YES];
        }
            break;
        case 3:
        {
            self.signalList=[NSMutableArray arrayWithArray:[XMLParser getSignalList:self.agency.agencyID subSystemID:self.subSystem.subSystemID timingPatternID:self.timingPattern.timingPatternID]];
            
            SignalDetailViewController *detailViewController=[[[SignalDetailViewController alloc] initWithNibNameAndSignal:@"SignalDetailViewController" agency:self.agency subSystem:self.subSystem timingPattern:self.timingPattern signalList:self.signalList signalIndex:indexPath.row automaticPlayOrNot:NO bundle:nil] autorelease];
            [detailViewController setTitle:@"Signal Detail"];
            [self.navigationController pushViewController:detailViewController animated:YES];
            [self.navigationController setNavigationBarHidden:NO animated:YES];
        }
            
        default:
            break;
    }
}

- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section==3) 
        return YES;
    
    return NO;
}
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath {
    if (destinationIndexPath.section!=3) {
        [self.tableView reloadData];
        return;
//        [self.tableView moveRowAtIndexPath:destinationIndexPath toIndexPath:sourceIndexPath];
    }
//    self.signalList=[NSMutableArray arrayWithArray:[XMLParser getSignalList:self.agency.agencyID subSystemID:self.subSystem.subSystemID timingPatternID:self.timingPattern.timingPatternID]];
//    Signal *tempOrigineSignal=[self.signalList objectAtIndex:sourceIndexPath.row];
//    [tempOrigineSignal retain];
////    Signal *tempDestinationSignal=[self.signalList objectAtIndex:destinationIndexPath.row];
    for (int i=0; i<self.signalList.count; i++) {
        [XMLParser removeSignal:[[self.signalList objectAtIndex:i] signalID] agencyID:self.agency.agencyID subSystemID:self.subSystem.subSystemID timingPatternID:self.timingPattern.timingPatternID];
    }
    if (destinationIndexPath.row>sourceIndexPath.row) {
        [self.signalList insertObject:[self.signalList objectAtIndex:sourceIndexPath.row] atIndex:destinationIndexPath.row+1];
        [self.signalList removeObjectAtIndex:sourceIndexPath.row];
//        [self.signalCellList insertObject:[self.signalCellList objectAtIndex:sourceIndexPath.row] atIndex:destinationIndexPath.row+1];
//        [self.signalCellList removeObjectAtIndex:sourceIndexPath.row];
    }else {
        [self.signalList insertObject:[self.signalList objectAtIndex:sourceIndexPath.row] atIndex:destinationIndexPath.row];
        [self.signalList removeObjectAtIndex:sourceIndexPath.row+1];
//        [self.signalCellList insertObject:[self.signalCellList objectAtIndex:sourceIndexPath.row] atIndex:destinationIndexPath.row];
//        [self.signalCellList removeObjectAtIndex:sourceIndexPath.row+1];
    }
//    [self.signalList exchangeObjectAtIndex:sourceIndexPath.row withObjectAtIndex:destinationIndexPath.row];
//    [self.signalList insertObject:tempOrigineSignal atIndex:destinationIndexPath.row];
//    [tempOrigineSignal release];
    for (int i=0; i<self.signalList.count; i++) {
        [XMLParser createSignal:[self.signalList objectAtIndex:i] agencyID:self.agency.agencyID subSystemID:self.subSystem.subSystemID timingPatternID:self.timingPattern.timingPatternID];
    }
    _signalListSection.contents=[[[NSMutableArray alloc] init] autorelease];
//    DynamicSignalCell *dynamicSignalCell=[self.dynamicSignalCellList objectAtIndex:indexPath.row];
    for (int i=0; i<self.signalList.count; i++) {
        [_signalListSection.contents addObject:[[self.signalList objectAtIndex:i] signalName]];
    }
    [self createSignalCellList];
    [self.tableView reloadData];
    
    
    
}

#pragma mark - AlertView delegate
- (void)alertView:(UIAlertView *)alertView
didDismissWithButtonIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0) {
        // Launch nuclear strike !
        
        //        NSArray *timerGroupList=[XMLParser getTimerGroupList];
        
        
        switch (alertView.tag) {
            case RemoveTimeRangeAlert:
            {
                int tag=self.publicSender;
                [self.timingPattern.timeRangeList removeObjectAtIndex:tag];
                [XMLParser updateTimingPattern:self.timingPattern agencyID:self.agency.agencyID subSystemID:self.subSystem.subSystemID];
                
                
                [self updateViewController];
            }
                break;
            case RemoveSignalAlert:
            {
                int tag=self.publicSender;
                [XMLParser removeSignal:[[self.signalList objectAtIndex:tag] signalID] agencyID:self.agency.agencyID subSystemID:self.subSystem.subSystemID timingPatternID:self.timingPattern.timingPatternID];
//                [self createSignalCellList];
                [self updateViewController];
            }
                break;
                
            default:
                break;
        }
        
    } else {
        // be nice with the world, maybe initiate some Ecological action as a bonus
    }
}
#pragma mark -TextField Delegate
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    self.timingPattern.cycleLength=self.timingPatternCycleTextView.text;
    [XMLParser updateTimingPattern:self.timingPattern agencyID:self.agency.agencyID subSystemID:self.subSystem.subSystemID];
    self.cycleLengthNameSection=[[[TableSection alloc]init] autorelease];
    
    //        _agencySection.contents=[[[NSMutableArray alloc] initWithArray:[XMLParser getAgencyList]] autorelease];
    self.cycleLengthNameSection.contents=[[[NSMutableArray alloc] init] autorelease];
    [self.cycleLengthNameSection.contents addObject:self.timingPattern.cycleLength];
    
    self.cycleLengthNameSection.header=@"Timing Pattern Cycle";
}
#pragma mark -TextView Delegate
- (BOOL)textViewShouldEndEditing:(UITextView *)textView{
    switch (textView.tag) {
        case NameTextView:
        {
            self.timingPattern.timingPatternName=self.timingPatternNameTextView.text;
            [XMLParser updateTimingPattern:self.timingPattern agencyID:self.agency.agencyID subSystemID:self.subSystem.subSystemID];
            self.timingPatternNameSection=[[[TableSection alloc]init] autorelease];
            
            //        _agencySection.contents=[[[NSMutableArray alloc] initWithArray:[XMLParser getAgencyList]] autorelease];
            self.timingPatternNameSection.contents=[[[NSMutableArray alloc] init] autorelease];
            [self.timingPatternNameSection.contents addObject:self.timingPattern.timingPatternName];
            
            self.timingPatternNameSection.header=@"Timing Pattern Name";
        }
            break;
        case CycleLengthTextView:
        {
            
            
        }
            break;
            
        default:
            break;
    }
    
    return YES;
}
#pragma mark - Customized functions
- (void) clickAddSignalButton:(id)sender
{
//    Signal *signal=[[[NEMASignal alloc] initWithCycleLength:self.timingPattern.cycleLength] autorelease];
//    [signal setSignalID:[XMLParser createSignalID:self.agency.agencyID subSystemID:self.subSystem.subSystemID timingPatternID:self.timingPattern.timingPatternID]];
////    [signal setCycleLength:self.timingPattern.cycleLength];
//    [signal setOffset:@"0"];
//    [signal setSignalName:@"New Signal"];
//    [XMLParser createSignal:signal agencyID:self.agency.agencyID subSystemID:self.subSystem.subSystemID timingPatternID:self.timingPattern.timingPatternID];
    
    Intersection *intersection=[[[Intersection alloc] init] autorelease];
    [intersection setIntersectionID:[XMLParser createIntersectionID:self.agency.agencyID subSystemID:self.subSystem.subSystemID]];
    [intersection setIntersectionName:@"New Intersection"];
    CLLocationCoordinate2D coordinate={0,0};
    [intersection setIntersectionCoordinate:coordinate];
    [XMLParser createIntersection:intersection agencyID:self.agency.agencyID subSystemID:self.subSystem.subSystemID];
    
    [self updateViewController];
}
- (void) clickAddTimeRangeButton:(id)sender
{
    TimeRange *timeRange=[[[TimeRange alloc] init] autorelease];
    [timeRange setBeginTime:@"00:00 AM"];
    [timeRange setEndTime:@"00:00 AM"];
    [self.timingPattern.timeRangeList addObject:timeRange];
    [XMLParser updateTimingPattern:self.timingPattern agencyID:self.agency.agencyID subSystemID:self.subSystem.subSystemID];
    [self updateViewController];
}
- (id) initWithNibNameAndTimingPattern:(NSString *)nibName agency:(Agency *)agency subSystem:(SubSystem *)subSystem timingPattern:(TimingPattern *)timingPattern bundle:(NSBundle *)nibBundle
{
    self=[super initWithNibName:nibName bundle:nibBundle];
    self.agency=agency;
    self.subSystem=subSystem;
    self.timingPattern=timingPattern;
    return self;
}
- (IBAction)textViewReturn:(id)sender
{
    
    [self.timingPatternNameTextView resignFirstResponder];
    [self.timingPatternCycleTextView resignFirstResponder];
}

- (void) removeSignal: (int)row
{
    self.publicSender=row;
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Confirmation" 
                                                    message:@"Delete the Signal?" 
                                                   delegate:self 
                                          cancelButtonTitle:@"YES"
                                          otherButtonTitles:@"NO",nil];
    [alert setTag:RemoveSignalAlert];
    [alert show];
    [alert release];
}
- (void) removeTimeRange: (int)row
{
    self.publicSender=row;
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Confirmation" 
                                                    message:@"Delete the time schedule?" 
                                                   delegate:self 
                                          cancelButtonTitle:@"YES"
                                          otherButtonTitles:@"NO",nil];
    [alert setTag:RemoveTimeRangeAlert];
    [alert show];
    [alert release];
}

- (void) updateViewController
{
    if (self.timingPatternNameSection) {
        self.timingPatternNameSection=[[[TableSection alloc]init] autorelease];
        
        self.timingPatternNameSection.contents=[[[NSMutableArray alloc] init] autorelease];
        [self.timingPatternNameSection.contents addObject:self.timingPattern.timingPatternName];
        
        self.timingPatternNameSection.header=@"Timing Pattern Name";
    }
    if (self.cycleLengthNameSection) {
        self.cycleLengthNameSection=[[[TableSection alloc]init] autorelease];
        
        self.cycleLengthNameSection.contents=[[[NSMutableArray alloc] init] autorelease];
        [self.cycleLengthNameSection.contents addObject:self.timingPattern.cycleLength];
        
        self.cycleLengthNameSection.header=@"Timing Pattern Cycle";
    }
    if(self.timeRangeListSection)
    {
        self.timeRangeListSection=[[[TableSection alloc]init] autorelease];
        
        self.timeRangeListSection.contents=[[[NSMutableArray alloc] init] autorelease];
        for (int i=0; i<self.timingPattern.timeRangeList.count; i++) {
            NSString * timeRangeString=[NSString stringWithFormat:@"%@ - %@",[[self.timingPattern.timeRangeList objectAtIndex:i] beginTime], [[self.timingPattern.timeRangeList objectAtIndex:i] endTime]];
            [self.timeRangeListSection.contents addObject:timeRangeString];
        }
        
        self.timeRangeListSection.header=@"Timing Pattern Schedule";
    }
    if(self.signalListSection)
    {
        self.signalListSection=[[[TableSection alloc]init] autorelease];
        self.signalList=[NSMutableArray arrayWithArray:[XMLParser getSignalList:self.agency.agencyID subSystemID:self.subSystem.subSystemID timingPatternID:self.timingPattern.timingPatternID]];
        [self createSignalCellList];
        self.signalListSection.contents=[[[NSMutableArray alloc] init] autorelease];
        for (int i=0; i<self.signalList.count; i++) {
            [self.signalListSection.contents addObject:[[self.signalList objectAtIndex:i] signalName]];
        }
        
//        self.signalListSection.header=@"   Signals           Active         Next";
        self.signalListSection.header=@"   Signals";
    }
//    if (!_linkButtonSection) {
//        _linkButtonSection=[[TableSection alloc] init];
//        _linkButtonSection.contents=[[[NSMutableArray alloc] init] autorelease];
//        [_linkButtonSection.contents addObject:@"Link Information"];
//        _linkButtonSection.header=@"Test";
//    }
    if (self.sections) {
        self.sections = [[[NSMutableArray alloc] init] autorelease];
        //        [_sections addObject:self.agencyNameSection];
        [self.sections addObject:self.timingPatternNameSection];
        [self.sections addObject:self.cycleLengthNameSection];
        [self.sections addObject:self.timeRangeListSection];
        [self.sections addObject:self.signalListSection];
//        [self.sections addObject:self.linkButtonSection];
    }
    [self.tableView reloadData];

}
- (void) updateTimer:(id) sender {
    int cycle=[self.timingPattern.cycleLength intValue];
    if (cycle>10) {
        int cycleTimer=[TrafficSignalTimer calculateCycleTimer:cycle offSet:0 syncTime:self.agency.syncTime standardTimeOff:[self.agency.baseTimeOffset intValue]];
        
        self.masterTimeLabel.text=[NSString stringWithFormat:@"              Master:%@ - %d",[TrafficSignalTimer getMasterTimeString:self.agency.baseTimeOffset], cycleTimer];;
        for (DynamicSignalCell* cell in self.dynamicSignalCellList) {
            [cell updateActivePhaseLabelWithMasterTime:cycleTimer];
        }
    }
    
//    [self updateRealTimeInformation];
    
}

- (void) clickEditScheduleButton
{
    if ([self.editScheduleButton.titleLabel.text isEqualToString:@"Edit"]) {
        [self.editScheduleButton setTitle:@"Done" forState:UIControlStateNormal];
        [self.tableView setEditing:YES];
    }else {
        [self.editScheduleButton setTitle:@"Edit" forState:UIControlStateNormal];
        [self.tableView setEditing:NO];
    }
}

- (void) clickDuplicateButton
{
    NSString *timingPatternName=[self.timingPattern.timingPatternName retain];
    NSString *timingPatternID=[self.timingPattern.timingPatternID retain];
    self.timingPattern.timingPatternName=[timingPatternName stringByAppendingFormat:@"-Duplicated"];
    self.timingPattern.timingPatternID=[XMLParser createTimingPatternID:self.agency.agencyID subSystemID:self.subSystem.subSystemID];
    [XMLParser duplicateTimingPattern:self.timingPattern originalTimingPatternID:timingPatternID agencyID:self.agency.agencyID subSystemID:self.subSystem.subSystemID];
    self.timingPattern.timingPatternName=timingPatternName;
    self.timingPattern.timingPatternID=timingPatternID;
    [timingPatternName release];
    [timingPatternID release];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Succeeded!"
                                                    message:@"This timing pattern has been successfully duplicated."
                                                   delegate:nil
                                          cancelButtonTitle:@"OK"
                                          otherButtonTitles:nil];
    [alert show];
    [alert release];
    
}

- (void) clickEditSignalButton
{
    if ([self.editSignalButton.titleLabel.text isEqualToString:@"Edit"]) {
        [self.editSignalButton setTitle:@"Done" forState:UIControlStateNormal];
        [self.tableView setEditing:YES];
    }else {
        [self.editSignalButton setTitle:@"Edit" forState:UIControlStateNormal];
        [self.tableView setEditing:NO];
    }
}

- (void) updateRealTimeInformation
{
    
    for (int i=0;i<self.signalList.count;i++) {
        Signal *signal=[self.signalList objectAtIndex:i];
        RealTimeSignalCell *signalCell=[self.signalCellList objectAtIndex:i];
        NSString *ring1ActivePhase=@"";
        NSString *ring1NextPhase=@"";
        NSString *ring2ActivePhase=@"";
        NSString *ring2NextPhase=@"";
        int offsetPhaseTime=0;
        int i=0;
        for (i=0; i<signal.ring1.phaseList.count; i++) {
            SignalPhase *phase=[signal.ring1.phaseList objectAtIndex:i];
            if ([signal.offsetPhase isEqualToString:phase.phaseID]) {
                if ([signal.offsetBorE isEqualToString:@"Green End"]) {
                    offsetPhaseTime=offsetPhaseTime+[phase.greenTime doubleValue];
                    
                }
                break;
            }
            offsetPhaseTime=offsetPhaseTime+[phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue];
        }
        if (i>=signal.ring1.phaseList.count) {
            offsetPhaseTime=0;
            for (i=0; i<signal.ring2.phaseList.count; i++) {
                SignalPhase *phase=[signal.ring2.phaseList objectAtIndex:i];
                if ([signal.offsetPhase isEqualToString:phase.phaseID]) {
                    if ([signal.offsetBorE isEqualToString:@"Green End"]) {
                        offsetPhaseTime=offsetPhaseTime+[phase.greenTime doubleValue];
                        
                    }
                    break;
                }
                offsetPhaseTime=offsetPhaseTime+[phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue];
            }
            if (i>=signal.ring2.phaseList.count) {
                offsetPhaseTime=0;
            }
        }
        int controllerTimer=[TrafficSignalTimer calculateCycleTimer:[signal.cycleLength intValue] offSet:([signal.offset intValue]-offsetPhaseTime) syncTime:self.agency.syncTime standardTimeOff:[self.agency.baseTimeOffset intValue]];
        int cycleTimer=controllerTimer;
        
//        signalCell.activePhaseLabel.text=[NSString stringWithFormat:@"NO Phase"];
        //        self.Ring1NextPhaseLabel.text=@"";
        
        for (int i=0; i<signal.ring1.phaseList.count; i++) {
            SignalPhase *phase=[signal.ring1.phaseList objectAtIndex:i];
            if (cycleTimer<=[phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue]) {
                ring1ActivePhase=[NSString stringWithFormat:@"%@%@:%.f/%.f",phase.phaseID,phase.phaseMovement,([phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue])-cycleTimer,([phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue])];
                
                if (i==signal.ring1.phaseList.count-1) {
                    SignalPhase *nextPhase=[signal.ring1.phaseList objectAtIndex:0];
                    ring1NextPhase=[NSString stringWithFormat:@"%@%@",[nextPhase phaseID],nextPhase.phaseMovement];
                }else {
                    SignalPhase *nextPhase=[signal.ring1.phaseList objectAtIndex:i+1];
                    ring1NextPhase=[NSString stringWithFormat:@"%@%@",[nextPhase phaseID],nextPhase.phaseMovement];
                }
                
                break;
            }
            
            cycleTimer=cycleTimer-([phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue]);
            //            self.Ring1CurrentPhaseLabel.text=[NSString stringWithFormat:@"NO Phase"];
        }

        
        cycleTimer=controllerTimer;
        
        
        //        self.Ring2NextPhaseLabel.text=@"";
        for (int i=0; i<signal.ring2.phaseList.count; i++) {
            SignalPhase *phase=[signal.ring2.phaseList objectAtIndex:i];
            if (cycleTimer<=[phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue]) {
                ring2ActivePhase=[NSString stringWithFormat:@"%@%@:%.f/%.f",phase.phaseID,phase.phaseMovement,([phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue])-cycleTimer,([phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue])];
                
                
                
                if (i==signal.ring2.phaseList.count-1) {
                    SignalPhase *nextPhase=[signal.ring2.phaseList objectAtIndex:0];
                    ring2NextPhase=[NSString stringWithFormat:@"%@%@",[nextPhase phaseID],nextPhase.phaseMovement];
                }else {
                    SignalPhase *nextPhase=[signal.ring2.phaseList objectAtIndex:i+1];
                    ring2NextPhase=[NSString stringWithFormat:@"%@%@",[nextPhase phaseID],nextPhase.phaseMovement];
                }
                break;
            }
            
            cycleTimer=cycleTimer-([phase.greenTime doubleValue]+[phase.yellowTime doubleValue]+[phase.allRedTime doubleValue]);
            //            self.Ring2CurrentPhaseLabel.text=@"NO Phase";
        }

        if ([ring1ActivePhase isEqualToString:@""]&&signal.ring1.phaseList.count>0) {
            SignalPhase *nextPhase=[signal.ring1.phaseList objectAtIndex:0];
            ring1NextPhase=[NSString stringWithFormat:@"%@%@",[nextPhase phaseID],nextPhase.phaseMovement];
        }
        if ([ring2ActivePhase isEqualToString:@""]&&signal.ring2.phaseList.count>0) {
            SignalPhase *nextPhase=[signal.ring2.phaseList objectAtIndex:0];
            ring2NextPhase=[NSString stringWithFormat:@"%@%@",[nextPhase phaseID],nextPhase.phaseMovement];
        }
        signalCell.activePhaseLabel.text=[NSString stringWithFormat:@"R1:%@\nR2:%@",ring1ActivePhase,ring2ActivePhase];
        signalCell.nextPhaseLabel.text=[NSString stringWithFormat:@"%@ \n%@ ",ring1NextPhase,ring2NextPhase];

    }
        
}

- (void) createSignalCellList
{
//    self.signalCellList=[[[NSMutableArray alloc] init] autorelease];
    self.dynamicSignalCellList=[[[NSMutableArray alloc] init] autorelease];
    for (Signal *signal in self.signalList) {
        static NSString *CellIdentifier = @"Cell";
//        static NSString *CellIdentifier2 = @"Cell2";
//        RealTimeSignalCell* signalCell = [[[RealTimeSignalCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        
        DynamicSignalCell* dynamicSignalCell=[[[DynamicSignalCell alloc] initWithSignal:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier signal:signal] autorelease];
        
        
//        signalCell.accessoryType=
//        UITableViewCellAccessoryDetailDisclosureButton;
//        signalCell.signalNameLabel.text=sectionContentString;
//        [signalCell setSelectionStyle:UITableViewCellEditingStyleNone];
//        [self.signalCellList addObject:signalCell];
        [self.dynamicSignalCellList addObject:dynamicSignalCell];
    }
}

- (void) goToMap:(id)sender
{
    ExploreMapViewViewController *detailViewController=[[[ExploreMapViewViewController alloc] initWithNibNameAndTimingPattern:@"ExploreMapViewViewController" timingPattern:self.timingPattern agency:self.agency subSystem:self.subSystem bundle:nil] autorelease];
    //    self.navigationItem.titleView=nil;
    //    [self.imageView removeFromSuperview];
    //    self.navigationItem.title=@"Home";
    [detailViewController setTitle:@"Signal Map"];
    [self.navigationController pushViewController:detailViewController animated:YES];
}

- (void) goToHome:(id)sender
{
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void) goToActiveMap:(id)sender
{
    ActiveSignalMapViewController *detailViewController=[[[ActiveSignalMapViewController alloc] initWithNibNameAndTimingPattern:@"ActiveSignalMapViewController" timingPattern:self.timingPattern agency:self.agency subSystem:self.subSystem bundle:nil] autorelease];
    //    self.navigationItem.titleView=nil;
    //    [self.imageView removeFromSuperview];
    //    self.navigationItem.title=@"Home";
    [detailViewController setTitle:@"Active Map"];
    [self.navigationController pushViewController:detailViewController animated:YES];
}

- (IBAction)goToTimeSpace:(id)sender
{
    if (self.signalList.count<=0) {
        return;
    }
    Signal *signal=[self.signalList objectAtIndex:0];
    TimeSpaceViewController *timeSpaceViewController=[[[TimeSpaceViewController alloc] initWithNibName:@"TimeSpaceViewController" bundle:nil agency:self.agency subsystem:self.subSystem timingPattern:self.timingPattern signal:signal direction:NORTHBOUND] autorelease];
    [timeSpaceViewController setTitle:@"Time Space View"];
    UINavigationController * parentController=self.navigationController;
    [parentController pushViewController:timeSpaceViewController animated:YES];
}

- (IBAction)goToTimeSpaceHistory:(id)sender
{
    if (self.signalList.count<=0) {
        return;
    }
    Signal *signal=[self.signalList objectAtIndex:0];
    GPSRecordListController *gpsRecordListController=[[[GPSRecordListController alloc] initWithNibName:@"GPSRecordListController" bundle:nil agency:self.agency subsystem:self.subSystem timingPattern:self.timingPattern signal:signal] autorelease];
    [gpsRecordListController setTitle:@"GPS Record List"];
    UINavigationController * parentController=self.navigationController;
    [parentController pushViewController:gpsRecordListController animated:YES];
}
@end
